package com.qiqidream.admin.system.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiqidream.admin.common.base.BaseController;
import com.qiqidream.admin.common.base.BaseEntity;
import com.qiqidream.admin.common.entity.AuthJson;
import com.qiqidream.admin.common.entity.PageEntity;
import com.qiqidream.admin.common.enums.MenuType;
import com.qiqidream.admin.common.utils.tree.TreeUtil;
import com.qiqidream.admin.system.model.dto.UserDto;
import com.qiqidream.admin.system.model.entity.Menu;
import com.qiqidream.admin.system.model.entity.Role;
import com.qiqidream.admin.system.model.vo.MenuVo;
import com.qiqidream.admin.system.model.vo.UserInfoVo;
import com.qiqidream.admin.system.model.entity.User;
import com.qiqidream.admin.system.model.vo.UserVo;
import com.qiqidream.admin.system.service.MenuService;
import com.qiqidream.admin.system.service.RoleService;
import com.qiqidream.admin.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 首页
 * @author QiQiDream
 * @since 2019/11/18 10:53
 */
@RestController
@Api(tags = "用户-接口")
@RequestMapping("/system/user")
public class UserController extends BaseController {
    @Resource
    UserService userService;

    @Resource
    MenuService menuService;

    @Resource
    RoleService roleService;

    @ApiOperation(value = "获取登录用户基本信息")
    @GetMapping("/info")
    public UserInfoVo getUserInfo() {
        User user = jwtUtil.getUserFromRequest(request);
        List<Long> roleIds = ObjectUtils.isEmpty(user.getAuthJson())?new ArrayList<>():user.getAuthJson().getRole();
        List<Long> menuIds = ObjectUtils.isEmpty(roleIds)?new ArrayList<>():roleService.listByIds(roleIds).stream().map(Role::getAuthJson).map(AuthJson::getMenu).flatMap(Collection::stream).distinct().collect(toList());

        UserInfoVo userInfoVo = new UserInfoVo();

        List<Menu> menuList = ObjectUtils.isEmpty(menuIds)?new ArrayList<>():menuService.list(new LambdaQueryWrapper<Menu>()
                .in(BaseEntity::getId,menuIds)
                .orderByAsc(Menu::getSort));

        List<Menu> list = menuList.stream().filter(data -> data.getType() != MenuType.BUTTON ).collect(toList());
        List<MenuVo> convert = Convert.convert(new TypeReference<List<MenuVo>>() {}, list);
        List<MenuVo> treeList = TreeUtil.getTreeList(0L, convert);


        List<Menu> ButtonMenus = menuList.stream().filter(data -> data.getType() == MenuType.BUTTON ).collect(toList());
        List<String> buttons = ButtonMenus.stream().map(Menu::getCode).collect(toList());

        userInfoVo.setNickName(user.getNickName());
        userInfoVo.setAvatar(user.getAvatar());
        userInfoVo.setPermissions(buttons);
        userInfoVo.setMenus(treeList);
        return userInfoVo;
    }

    @ApiOperation(value = "查询用户列表")
    @GetMapping("")
    public PageEntity<UserVo> getUsers(@RequestParam(value = "page", defaultValue = "1") Long page,
                                       @RequestParam(value = "count", defaultValue = "10") Long count,
                                       @RequestParam(value = "deptId",required = false) Long deptId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(deptId)){
            wrapper.eq(User::getDeptId,deptId);
        }
        IPage<User> iPage = userService.page(new Page<>(page, count),wrapper);
        return new PageEntity<>(iPage.getTotal(),Convert.convert(new TypeReference<List<UserVo>>() {}, iPage.getRecords()));
    }

    @ApiOperation(value = "添加用户")
    @PostMapping("")
    public Boolean addUser(@RequestBody UserDto userDto) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setPassword(passwordEncoder.encode("123456"));
        userService.save(user);
        return true;
    }

    @ApiOperation(value = "编辑用户")
    @PutMapping("")
    public Boolean editUser(@RequestBody UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        userService.updateById(user);
        return true;
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{id}")
    public Boolean removeUser(@PathVariable Long id) {
        userService.removeById(id);
        return true;
    }


}
